package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryShopType() {
        //1.从redis中查询商铺缓存
        String shopTypeJSon = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_TYPE_LIST_KEY);
        //2.判断是否存在
        if(StrUtil.isNotBlank(shopTypeJSon)){
            //将json转为javaList对象
            List<ShopType> list = JSONUtil.toList(shopTypeJSon, ShopType.class);
            //3.存在直接返回
            return Result.ok(list);
        }

        //4.redis中不存在, 查询数据库
        List<ShopType> list = query().orderByAsc("sort").list();
        //5,判断数据库是否存在
        if(list == null){
            //6.不存在,返回错误
            return Result.fail("分类不存在");
        }
        //7.数据库中存在,将查询的信息写入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_TYPE_LIST_KEY, JSONUtil.toJsonStr(list));

        //8.返回数据
        return Result.ok(list);
    }
}
